package io.renren.modules.user.service.impl;

import io.renren.common.exception.RRException;
import io.renren.modules.api.dao.TokenDao;
import io.renren.modules.driver.dao.SjDriverDao;
import io.renren.modules.driver.entity.SjDriverEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import io.renren.modules.user.dao.WebUserDao;
import io.renren.modules.user.entity.UserEntity;
import io.renren.modules.user.service.WebUserService;
import org.springframework.transaction.annotation.Transactional;


@Service("webUserService")
public class WebUserServiceImpl implements WebUserService {
	@Autowired
	private WebUserDao userDao;

	@Autowired
	private SjDriverDao sjDriverDao;

	@Autowired
	private TokenDao tokenDao;
	
	@Override
	public UserEntity queryObject(Long userId){
		return userDao.queryObject(userId);
	}
	
	@Override
	public List<UserEntity> queryList(Map<String, Object> map){
		return userDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return userDao.queryTotal(map);
	}
	
	@Override
	public void save(UserEntity user){
		userDao.save(user);
	}

	@Override
	public void update(UserEntity user){
		userDao.update(user);
	}
	
	@Override
	public void delete(Long userId){
		userDao.delete(userId);
	}
	
	@Override
	public void deleteBatch(Long[] userIds){
		userDao.deleteBatch(userIds);
	}

	@Override
	@Transactional
	public void becomeDriver(Long[] userIds) {

		//先往司机表里插入数据
		for(Long userId : userIds){
			UserEntity user = userDao.queryObject(userId);
			SjDriverEntity driverTemp = sjDriverDao.queryObjectByUserName(user.getUsername());
			if (driverTemp != null) {
				throw new RRException(driverTemp.getUsername()+"已经是司机了");
			}
			SjDriverEntity driver = new SjDriverEntity();
			driver.setUsername(user.getUsername());
			driver.setMobile(user.getPhone());
			driver.setSex(user.getSex());
			driver.setNickname(user.getNickname());
			driver.setRealname(user.getRealname());
			driver.setAvatar(user.getAvatar());
			sjDriverDao.save(driver);
		}
		//在用户表里删除这些已经成为司机的用户
		userDao.deleteBatch(userIds);
		tokenDao.deleteBatch(userIds);

	}


}
